package pl.edu.pk.cc.client.admin;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.Session;

import pl.edu.pk.cc.client.CCPage;
import pl.edu.pk.cc.common.dto.CCClientDTO;
import pl.edu.pk.cc.common.dto.CCEmploymentDTO;
import pl.edu.pk.cc.common.dto.CCLoginDataDTO;
import pl.edu.pk.cc.common.dto.CCScriptsDTO;
import pl.edu.pk.cc.common.dto.CCWorkerDTO;
import pl.edu.pk.cc.common.util.CCPermissions;
import pl.edu.pk.cc.server.hibernate.CCHibernateUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.util.List;

/**
 * Servlet implementation class CCAdminFunctions
 */
public class CCAdminFunctions extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static CCWorkerDTO worker;
	HttpSession sess;
	static Session s = CCHibernateUtil.getSessionFactory().getCurrentSession();
	String tresc = "";
	String[] params;
	
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-DD");
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CCAdminFunctions() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		sess = request.getSession();

		
		if(type == null){
			try {
				@SuppressWarnings("unchecked")
				List<FileItem> fields = upload.parseRequest(request);
				type = fields.get(0).getString();
				tresc = fields.get(1).getString();
				if(fields.size() > 2){
					params = new String[2];
					params[0] = fields.get(2).getString();
					if(fields.size() == 3)
						params[1] = "no";
					else
						params[1] = "yes";
				}
			} catch (FileUploadException e) {
				
			}
		}
		switch(type){
		case "dodaj":
			String username = request.getParameter("username");
			String email = request.getParameter("email");
			String name = request.getParameter("name");
			String surname = request.getParameter("surname");
			String address = request.getParameter("address");
			Long pesel = null;
			Long lenght = null;
			Float salary = null;
			try {
				pesel = Long.parseLong(request.getParameter("pesel"));
				lenght = Long.parseLong(request.getParameter("lenght"));
				salary = Float.parseFloat(request.getParameter("salary"));
			}
			catch(NumberFormatException e){
				sess.setAttribute("success", 6); // blad parsowania
				//response.sendRedirect("Index?strona=dodaj");
			}
			Date birthdate = new Date();
			Date startDate = new Date();
			try {
				birthdate = df.parse(request.getParameter("birthdate"));
				startDate = df.parse(request.getParameter("startDate"));
			} catch (ParseException e) {
				sess.setAttribute("success", 5); // blad daty
				//response.sendRedirect("Index?strona=dodaj");
			}
			if(!(username.equals("") || email.equals("") || name.equals("") || surname.equals("") || address.equals(""))){
				CCPermissions perm = CCPermissions.valueOf(request.getParameter("perm").toUpperCase());

				CCWorkerDTO worker = new CCWorkerDTO(name,surname,pesel,birthdate,address);
				CCLoginDataDTO login = new CCLoginDataDTO(username,pesel.toString(),email,perm);
				CCEmploymentDTO emp = new CCEmploymentDTO(startDate,lenght,salary);

				worker.setLogin(login);
				worker.setEmp(emp);
				login.setWorker(worker);
				emp.setWorker(worker);


				s = CCHibernateUtil.getSessionFactory().getCurrentSession();
				s.beginTransaction();
				Query q = s.createQuery("from CCLoginDataDTO where username=:user").setParameter("user", username);
				if(q.list().isEmpty()){
					Long id = (Long)s.save(worker);
					s.flush();
					s.getTransaction().commit();

					if(id != 0){
						sess.setAttribute("success", 1); // dodano
					}
					else {
						sess.setAttribute("success", 2); // nie dodano - blad bazy
					}
				}
				else {
					sess.setAttribute("success", 3); // uzytkownik istnieje
				}
			}
			else {
				sess.setAttribute("success", 4); // nie podano wszystkich danych
			}
			response.sendRedirect("Index?strona=dodaj");
			break;
		case "wyszukaj":
			String username_s = request.getParameter("username");
			worker = getWorker(username_s);
			if(worker != null){
				CCAdminContent.setWorkerToEdit(worker);
				sess.setAttribute("success", 1); // znaleziono uzytkownika
				CCPage.setStep(1);
			}
			else {
				sess.setAttribute("success", 2); // nie znaleziono
				CCPage.setStep(0);
			}
			response.sendRedirect("Index?strona=modyfikuj");
			break;
		case "modyfikuj":
			String email1 = request.getParameter("email");
			String name1 = request.getParameter("name");
			String surname1 = request.getParameter("surname");
			String address1 = request.getParameter("address");
			Long pesel1 = null;
			Long lenght1 = null;
			Float salary1 = null;
			try {
				pesel1 = Long.parseLong(request.getParameter("pesel"));
				lenght1 = Long.parseLong(request.getParameter("lenght"));
				salary1 = Float.parseFloat(request.getParameter("salary"));
			}
			catch(NumberFormatException e){
				sess.setAttribute("success", 6); // blad parsowania
				CCPage.setStep(1);
				//response.sendRedirect("Index?strona=dodaj");
			}
			Date birthdate1 = new Date();
			Date startDate1 = new Date();
			try {
				birthdate1 = df.parse(request.getParameter("birthdate"));
				startDate1 = df.parse(request.getParameter("startDate"));
			} catch (ParseException e) {
				sess.setAttribute("success", 5); // blad daty
				CCPage.setStep(1);
				//response.sendRedirect("Index?strona=dodaj");
			}
			if(!(email1.equals("") || name1.equals("") || surname1.equals("") || address1.equals(""))){
				CCPermissions perm1 = CCPermissions.valueOf(request.getParameter("perm").toUpperCase());

				CCWorkerDTO worker1 = worker;
				CCLoginDataDTO login1 = worker.getLogin();
				CCEmploymentDTO emp1 = worker.getEmp();

				worker1.updateWorker(name1, surname1, pesel1, birthdate1, address1);
				login1.updateLogin(email1, perm1);
				emp1.updateEmp(startDate1, lenght1, salary1);
				s = CCHibernateUtil.getSessionFactory().getCurrentSession();
				s.beginTransaction();
				s.update(worker1);
				s.getTransaction().commit();
				sess.setAttribute("success", 3); // pomyslnie zmodyfikowano
				CCPage.setStep(0);
			}
			else {
				sess.setAttribute("success", 4); // nie podano wszystkich danych
				CCPage.setStep(1);
			}
			response.sendRedirect("Index?strona=modyfikuj");
			break;
		case "zmien_usera":
			sess.setAttribute("success", 0);
			CCPage.setStep(0);
			response.sendRedirect("Index?strona=modyfikuj");
			break;
		case "haslo":
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			CCLoginDataDTO login = worker.getLogin();
			login.setPassword(worker.getPesel().toString());
			s.update(worker);
			s.getTransaction().commit();
			CCPage.setStep(0);
			sess.setAttribute("success", 7);
			response.sendRedirect("Index?strona=modyfikuj");
			break;
		case "usun":
			String username_u = request.getParameter("username");
			worker = getWorker(username_u);
			sess.setAttribute("worker", worker);
			if(worker != null){
				CCAdminContent.setWorkerToEdit(worker);
				sess.setAttribute("success", 1); // znaleziono uzytkownika
				CCPage.setStep(1);
			}
			else {
				sess.setAttribute("success", 2); // nie znaleziono
				CCPage.setStep(0);
			}

			response.sendRedirect("Index?strona=usun");
			break;
		case "usun_t":
			CCWorkerDTO worker = (CCWorkerDTO)sess.getAttribute("worker");
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			s.delete(worker);
			s.flush();
			s.getTransaction().commit();
			
			sess.setAttribute("success", 3); // usunieto uzytkownika
			CCPage.setStep(0);
			response.sendRedirect("Index?strona=usun");
			break;
		case "usun_n":
			sess.setAttribute("success", 0);
			CCPage.setStep(0);
			response.sendRedirect("Index?strona=usun");
			break;
		case "users":
			String[] clients = tresc.split(";");
			
			CCClientDTO client = new CCClientDTO();
			int v=0;
			boolean succ = false;
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			System.out.println(clients.length);
			for(int i = 0; i < clients.length ; i++){
				String[] values = clients[i].split(",");
				System.out.println(values.length);
				if(values.length != 5){
					succ = false;
					break;
				}
				else {
					client.setName(values[0].trim());
					client.setSurname(values[1]);
					client.setPhoneNumber(Long.valueOf(values[2]));
					try {
						client.setBirthDate(df.parse(values[3]));
					} catch (ParseException e) {
						sess.setAttribute("success", 3); // blad daty
						response.sendRedirect("Index?strona=users");
						break;
					}
					client.setAddress(values[4]);
					s.save(client);
					client = new CCClientDTO();
					v++;
					if(v % 20 == 0){
						s.flush();
					}
					succ = true;
				}
			}
			s.getTransaction().commit();
			
			if(succ == true){
				sess.setAttribute("success", 1); // wgrano
			}
			else {
				sess.setAttribute("success", 2); // nie wgrano - blad
			}
			
			response.sendRedirect("Index?strona=users");
			break;
		case "script":
			CCScriptsDTO script = new CCScriptsDTO();
			boolean accept;
			if(params[1].equals("no")){
				accept = false;
			}
			else {
				accept = true;
			}
			script.setAccept(accept);
			script.setScript(tresc);
			script.setType(params[0]);
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			long id = (Long)s.save(script);
			s.flush();
			s.getTransaction().commit();
			if(id > 0){
				sess.setAttribute("success", 1); // wgrano skrypt
			}
			else {
				sess.setAttribute("success", 2); // nie wgrano - blad
			}
			response.sendRedirect("Index?strona=skrypt");
		break;
		}


	}
	public static CCWorkerDTO getWorker(String user){
		CCWorkerDTO worker = null;
		
		s = CCHibernateUtil.getSessionFactory().getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from CCWorkerDTO w where w.login.username=:user").setParameter("user", user);
		if(!q.list().isEmpty()){
			if(q.list().get(0) instanceof CCWorkerDTO)
				worker = (CCWorkerDTO)q.list().get(0);
		}
		s.getTransaction().commit();
		return worker;
	}
}
